package org.jeecg.modules.mall.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.appuser.constant.PayTypeConstant;
import org.jeecg.modules.appuser.constant.TaskNamesConstant;
import org.jeecg.modules.appuser.entity.TbUserVip;
import org.jeecg.modules.appuser.entity.TbUserWallet;
import org.jeecg.modules.appuser.entity.TbUserWalletDetail;
import org.jeecg.modules.appuser.service.ITbUserIntegralService;
import org.jeecg.modules.appuser.service.ITbUserVipService;
import org.jeecg.modules.appuser.service.ITbUserWalletDetailService;
import org.jeecg.modules.appuser.service.ITbUserWalletService;
import org.jeecg.modules.mall.entity.TbMnOrder;
import org.jeecg.modules.mall.entity.TbMnUser;
import org.jeecg.modules.mall.service.ITbMnAdzoneService;
import org.jeecg.modules.mall.service.ITbMnOrderService;
import org.jeecg.modules.mall.service.ITbMnUserService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TestupGradeData {

    @Autowired
    @Lazy(true)
    private ITbMnOrderService tbMnOrderService;

    @Autowired
    private ITbMnAdzoneService tbMnAdzoneService;

    @Autowired
    private ITbMnUserService tbMnUserService;

    @Autowired
    private ITbUserVipService tbUserVipService;

    @Autowired
    private ITbUserWalletService tbUserWalletService;

    @Autowired
    private ITbUserWalletDetailService tbUserWalletDetailService;

    @Autowired
    private ITbUserIntegralService tbUserIntegralService;

    @Autowired
    private ISysDictService sysDictService;

    public void test(String trade_id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("trade_id", trade_id);
        TbMnOrder tbMnOrder = tbMnOrderService.getOne(queryWrapper);
        updateWalletData(tbMnOrder, queryWrapper);

    }

    public void updateWalletData(TbMnOrder tbMnOrder, QueryWrapper queryWrapper) {
        if (3 == tbMnOrder.getTkStatus()) {
            //返佣
            String adzoneId = tbMnOrder.getAdzoneId();
            //查询用户
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("trade_id", tbMnOrder.getTradeId());
            TbMnOrder tbMnOrder1 = tbMnOrderService.getOne(queryWrapper1);
            if (tbMnOrder1.getRebateStatus() == 0) {
                TbMnUser tbMnUser = tbMnAdzoneService.getOneByAdzone(adzoneId);
                tbMnOrder.setRebateStatus(1);
                //返佣三级
                int rebate_layer_num = 3;
                RebateUser(tbMnOrder1, tbMnUser, rebate_layer_num);
                //  增加个人积分一次
                if (null != tbMnUser) {
                    Map<String, Object> resultData1 = tbUserIntegralService.doActionTask(tbMnUser.getId(), TaskNamesConstant.Task_SELF_PURCHASE_GOODS);
                    log.info("增加个人积分一次--->" + resultData1.toString());

                }


            }

        }
        tbMnOrderService.update(tbMnOrder, queryWrapper);
    }

    //升级用户等级
    private boolean upgradeUserGrade(TbMnUser tbMnUser) {



        BigDecimal profit = new BigDecimal(0);
        if (null != tbMnUser) {
            QueryWrapper userWalletQueryWrapper = new QueryWrapper();
            userWalletQueryWrapper.eq("user_id", tbMnUser.getId());
            userWalletQueryWrapper.eq("pay_from", PayTypeConstant.PAYFORM_REBATE);
            List<TbUserWalletDetail> tbUserWalletDetailList = tbUserWalletDetailService.list(userWalletQueryWrapper);
            if (null != tbUserWalletDetailList && tbUserWalletDetailList.size() > 0) {
                for (TbUserWalletDetail tbUserWalletDetail : tbUserWalletDetailList) {
                    profit = profit.add(tbUserWalletDetail.getPayNumber());
                }

            }
            log.info(tbMnUser.getPhone()+"用户升级---------------------------------->" + profit);
            //得到上一等级
            TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
            int next_srot = tbUserVip.getSort() + 1;
            QueryWrapper vipQueryWrapper = new QueryWrapper();
            vipQueryWrapper.eq("sort", next_srot);
            TbUserVip next_tbUserVip = tbUserVipService.getOne(vipQueryWrapper);
            if (null == next_tbUserVip) {
                log.info("你已经是最高等级了");
            } else {

                BigDecimal next_tbUserVipBalanceMin = next_tbUserVip.getInviteProfit();
                log.info(tbMnUser.getPhone()+"用户升级------profit.compareTo(next_tbUserVipBalanceMin---->"+profit.compareTo(next_tbUserVipBalanceMin));
                if (profit.compareTo(next_tbUserVipBalanceMin) >= 0) {
                    //升级
                    tbMnUser.setVipId(next_tbUserVip.getId());
                    tbMnUser.setVipName(next_tbUserVip.getVipName());
                    String bigDecimal = next_tbUserVip.getFirstRebate().multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
                    tbMnUser.setOwnRate(bigDecimal);
                    tbMnUserService.updateById(tbMnUser);
                    log.info(tbMnUser.getPhone()+"用户升级---------完成------------------------->\n");
                    log.info("{}升级成功,手机号码{}", tbMnUser.getAccount(), tbMnUser.getPhone());
                    return true;
                }
            }
        }

        return false;
    }

    private void RebateUser(TbMnOrder tbMnOrder1, TbMnUser tbMnUser, Integer rebate_layer_num) {

        if (rebate_layer_num > 0) {
            if (null != tbMnUser) {
                //得到用户等级
                if (null != tbMnUser) {
                    TbUserVip tbUserVip = tbUserVipService.getById(tbMnUser.getVipId());
                    BigDecimal firstRebate = null;
                    if (rebate_layer_num == 3) {
                        firstRebate = tbUserVip.getFirstRebate();
                    }
                    if (rebate_layer_num == 2) {
                        firstRebate = tbUserVip.getSecondRebate();
                    }
                    if (rebate_layer_num == 1) {
                        firstRebate = tbUserVip.getThirdRebate();
                    }

                    String totalCommissionFee = tbMnOrder1.getTotalCommissionFee();
                    BigDecimal totalCommissionFeedec = new BigDecimal(totalCommissionFee);
                    BigDecimal upperFirstFee = firstRebate.multiply(totalCommissionFeedec);
                    if (upperFirstFee.compareTo(new BigDecimal(0)) > 0) {
                        TbUserWallet tbUserWallet = tbUserWalletService.getOneByUser_id(tbMnUser.getId());
                        synchronized (tbUserWallet) {
                            BigDecimal upperFirstWalletBalance = tbUserWallet.getBalance();
                            BigDecimal new_upperFirstWalletBalance = upperFirstWalletBalance.add(upperFirstFee);
                            tbUserWallet.setBalance(new_upperFirstWalletBalance);

                            if (saveUserWalletDetail(tbUserWallet, upperFirstFee, tbMnUser.getId())) {
                                //资产更新成功
                                if (tbUserWalletService.updateById(tbUserWallet)) {
                                    rebate_layer_num = rebate_layer_num - 1;
                                    //查询它的被邀请人,进行返佣
                                    TbMnUser inviteesUpperFirst = tbMnUserService.getInviteesUpperFirst(tbMnUser);
                                    if (null != inviteesUpperFirst) {
                                        RebateUser(tbMnOrder1, inviteesUpperFirst, rebate_layer_num);
                                    }
                                }
                            }
                        }
                    }
                }
                //用户升级
                upgradeUserGrade(tbMnUser);

            }

        }
    }

    private boolean saveUserWalletDetail(TbUserWallet tbUserWallet, BigDecimal newBalance, String fromUserId) {
        TbUserWalletDetail tbUserWalletDetail = new TbUserWalletDetail();
        tbUserWalletDetail.setPayFrom(PayTypeConstant.PAYFORM_REBATE);
        tbUserWalletDetail.setPayType(PayTypeConstant.PAYTYPE_INCOME);
        tbUserWalletDetail.setPayNumber(newBalance);
        tbUserWalletDetail.setWalletId(tbUserWallet.getId());
        tbUserWalletDetail.setUserId(tbUserWallet.getUserId());
        tbUserWalletDetail.setFromUser(fromUserId);
        tbUserWalletDetail.setBalance(tbUserWallet.getBalance());
        tbUserWalletDetailService.save(tbUserWalletDetail);
        return true;
    }
}
